﻿#include "common/logger/logger.h"
#include "cxidropdownbutton/cxidropdownbutton_p.h"
#include <QAction>
#include <controls/dropdownbutton/cxidropdownbutton.h>

CxiDropDownButton::CxiDropDownButton(QWidget* parent)
	: QToolButton(parent),
	  d_ptr(new CxiDropDownButtonPrivate(this))
{
	Q_D(CxiDropDownButton);
	setPopupMode(MenuButtonPopup);
	setMenu(d->menu);
}

CxiDropDownButton::~CxiDropDownButton() = default;

void CxiDropDownButton::addItem(const QString& text,
								const QIcon& icon,
								std::function<void()> callback,
								int index)
{
	Q_D(CxiDropDownButton);
	auto* action = new QAction(icon, text, this);

	const QList<QAction*> acts = d->menu->actions();
	for (QAction* existingAction: acts)
	{
		if (existingAction->text() == text)
		{
			LOG_ERROR(text + "已存在");
			return;
		}
	}
	if (index >= 0 && index < acts.size())
	{
		QAction* before = acts.at(index);
		d->menu->insertAction(before, action);
	}
	else
	{
		d->menu->addAction(action);
	}

	if (callback)
	{
		connect(action, &QAction::triggered, this,
				[cb = std::move(callback)](bool) {
					if (cb) cb();
				});
	}
}

void CxiDropDownButton::addItem(QAction* action, int index)
{
	Q_D(CxiDropDownButton);
	if (!action) return;
	const QList<QAction*> acts = d->menu->actions();
	for (QAction* existingAction: acts)
	{
		if (existingAction->text() == action->text())
		{
			LOG_ERROR(action->text() + "已存在");
			return;
		}
	}
	action->setParent(this);
	if (index >= 0 && index < acts.size())
	{
		QAction* before = acts.at(index);
		d->menu->insertAction(before, action);
	}
	else
	{
		d->menu->addAction(action);
	}
}

void CxiDropDownButton::addSeparator(int index)
{
	Q_D(CxiDropDownButton);
	if (index < 0 || index >= d->menu->actions().size())
	{
		d->menu->addSeparator();
		return;
	}
	d->menu->insertSeparator(d->menu->actions().at(index));
}
